var ENTS = {}, W = 500, H = 400, HW = W / 2, HH = H / 2, player, LAST, CURRENT;
var MapTiles = [], MAPTILE = 400, currentTile, lastTile; 

window.onload = function() {

	Crafty.load(["assets/sprites.png"], function() {
		initSprites();
		init();
	});
	function initMap() {
	loadMapTile("-22.22653,-45.93681", 0, 0);
	
	// for(var obj in MAP) {
	// var pos = obj.split(",");
	// ENTS[obj] = Crafty.e("2D, Canvas, " + MAP[obj]).attr({
	// x : pos[0] * 32,
	// y : pos[1] * 32
	// });
	//
	// //make houses solid
	// if(MAP[obj].substr(0, 5) === "house") {
	// ENTS[obj].addComponent("Solid, Collision").collision();
	// }
	// }
	}
	
	function init() {
		Crafty.init(400, 400);
		Crafty.canvas.init();
		initMap();
		CurrentTile = MapTiles[0];
		player = Crafty.e("2D, Canvas, player, Keyboard, Collision, Multiway").origin("center");
		player.attr({x : 200, y : 200, _active : true});
		player.collision(new Crafty.polygon([[1, 19], [2, 14], [9, 14], [13, 9], [22, 10], [24, 14], [31, 15], [30, 21], [2, 20]]));
		player.multiway(3, {UP_ARROW: -90, DOWN_ARROW: 90, RIGHT_ARROW: 0, LEFT_ARROW: 180});
		// player.bind("EnterFrame", function(e) {
			// if(!this._active)
				// return;
// 
			// var angle = this._rotation * (Math.PI / 180), vx = Math.sin(angle), vy = -Math.cos(angle);
// 
			// if(this.isDown(Crafty.keys.W) || this.isDown(Crafty.keys.UP_ARROW)) {
				// this.x += vx * 3.5;
				// this.y += vy * 3.5;
			// } else if(this.isDown(Crafty.keys.S) || this.isDown(Crafty.keys.DOWN_ARROW)) {
				// this.x += -vx * 1.5;
				// this.y += -vy * 1.5;
			// }
// 
			// var collision = this.hit("Solid"), item;
// 
			// this.intersect()
			// if(collision) {
				// item = collision[0];
// 
				// this.x += Math.ceil(item.normal.x * -item.overlap);
				// this.y += Math.ceil(item.normal.y * -item.overlap);
			// }
// 
		// });
		
		player.bind("KeyDown", function(e) {
			if(e.keyCode === Crafty.keys.ENTER || e.keyCode === Crafty.keys.F) {
				var search = this.mbr(), results = Crafty.map.search({
					_x : search._x - 20,
					_y : search._y - 20,
					_w : search._w + 20,
					_h : search._h + 20,
				}, true), i = 0, l = results.length;

				for(; i < l; ++i) {
					if(results[i].has("Car")) {
						CURRENT = results[i];
						results[i]._active = true;
						this._active = false;
						this.visible = false;
						LAST = e.timeStamp;

						break;
					}
				}
			}
		});
		CURRENT = player;

		Crafty.addEvent(this, "mousemove", function(e) {
			var pos = Crafty.DOM.translate(e.clientX, e.clientY);
			player.rotation = ~~(Math.atan2(pos.y - player._y, pos.x - player._x) * (180 / Math.PI)) + 90;
		});
		car = Crafty.e("2D, Canvas, car_player, Car").attr({
			x : 200,
			y : 200
		});

		//Global viewport scrolling
		Crafty.bind("EnterFrame", function() {
			if(!CURRENT)
				return;
	// $("#debug").html(Crafty.viewport.x + " "+Crafty.viewport.y );
			//position of the viewport
			var vpx = (CURRENT._x - HW), vpy = (CURRENT._y - HH);

			//Max x in map * 32 - Crafty.viewport.width = 1164
			//	if(vpx > 0 && vpx < 1196) {
			Crafty.viewport.x = -vpx;
			//}

			//	if(vpy > 0 && vpy < 368) {
			Crafty.viewport.y = -vpy;
			
			//	}
		
			if( Crafty.viewport.x > (currentTile.x + currentTile.w)/2){
				if(!currentTile._rightTile){ 
					currentTile.loadRightTile();
					currentTile._rightTile = true;
					console.log("right");
				}
			}
			
			if( Crafty.viewport.x <(this.x + this.w)/2){
				if(!currentTile._leftTile){ 
					currentTile.loadLeftTile();
					currentTile._leftTile = true;
					console.log("left");
				}
			}
				
		});
	};

	Crafty.c("MapTile", {
		_lat : 0,
		_lon : 0,
		_latlon : 0,
		_initx : 0,
		_inity : 0,
		_map : 0,
		_walls : [],
		_active : false,
		_upTile : false,
		_rightTile : false,
		_downTile : false,
		_leftTile : false,
		
		init : function(){
			this.requires("2D, Color, Canvas, Image, Collision");
		},
		
		maptile: function(latlon, polys,initx,inity){
			var cord = latlon.split(",");
			this._lat = cord[0];
			this._lon = cord[1];
			this._latlon = latlon;
			this._map = this;
			this._polys = polys;
			this._wallActive = false;
			this._walls = [];
		
			for(var i = this._polys.length - 1; i >= 0; i--) {
						var wall = Crafty.e("2D, Canvas, Collision, Solid").attr({
								x : initx,
								y : inity,
								w : MAPTILE,
								h : MAPTILE,
								_active : false,
								visible : false
							}).collision(new Crafty.polygon(polys[i]));
							var id = wall[0];
							//walls[id] = wall;
							//this._walls[i] = wall[0];
							this._walls[i] = wall;
							}
							
			this.attr({x:initx, y:inity, z: -1, w : MAPTILE, h : MAPTILE, _active:true});
			Crafty.load(["maps/"+this._latlon+".png"], function (e) {
				
				if( MapTiles[e])
			  	MapTiles[e].image([e]);
			  	
			  	console.log(MapTiles.length);
			  		if(MapTiles.length > 2){
				console.log(maptile);
				var maptile = MapTiles.pop();
				 for (var i = maptile._walls.length - 1; i >= 0; i--){
			  			maptile._walls[i].destroy();
			  		}
		  			maptile.destroy();
				}
			});
			

			//this.loadLeftTile();
			this.bind("EnterFrame", function() {
				var collision = this.hit("player");
				if(collision) {
					if(currentTile != this){
						currentTile = this;
					}
				}
          		  // $("#debug").html(CurrentTile._latlon);
          		// $("#debug").html((this.y + this.h) +" "+ Crafty.viewport.y);
          	//	$("#debug").html("XX");
        	// console.log(Crafty.viewport.y + " " + Crafty.viewport.x + " " +this._latlon +" "+(((this.y + this.h) < (Crafty.viewport.y)) ||
       			 	// (this.y > (Crafty.viewport.y + 395))   	   ||
        			// ((this.x + this.w) < Crafty.viewport.x)	   ||
        			// (this.x > (Crafty.viewport.x + 400))		));s

$("#debug").html(Crafty.viewport.x);
				//$("#debug").html(Crafty.viewport.x > (this.x + this.w));
				// console.log(Crafty.viewport.x + " "+ (this.x + this.w));
				
			
				
				if(!(((this.y + this.h) < (Crafty.viewport.y)) ||
       			 	(this.y > (Crafty.viewport.y + MAPTILE))   	   ||
        			((this.x + this.w) < Crafty.viewport.x)	   ||
        			(this.x > (Crafty.viewport.x + MAPTILE))		)){
					//	$("#debug").html(currentTile._latlon);
						
						if(this._wallActive == false){ 
					
						this._wallActive = true;
						}
					}else{
						if(this._wallActive == true){ 
						for (var i = this._walls.length - 1; i >= 0; i--){
						// console.log(walls[this._walls[i]]);
						this._walls[i].destroy();
						
						};
						this._wallActive = false;
						this.destroy();
						}
					}
// 	
				// this.intersect()
				// if(collision) {
					// item = collision[0];
					// if(currentTile != this){
					// lastTile = currentTile ;
						// var solids = Crafty("Solid");
						// if( solids.length > 1)
						// for (var i = solids.length - 1; i >= 0; i--){
						  // if(walls[solids[i]] != undefined)
						  // walls[solids[i]].removeComponent("Solid");
						// };
						// currentTile = this;
							// for (var i = this._walls.length - 1; i >= 0; i--){
							// // console.log(walls[this._walls[i]]);
							 // walls[this._walls[i]].addComponent("Solid");
							// };
						// $("#debug").html(player.x + " " + player.y + " " + this._latlon + "<br>" );
					// }
				// }
					//$("#debug").html(player.x + " " + player.y);
				// if(player.x > this.x && player.x < this.w || player.y > this.y && player.y < this.h){
						// $("#debug").html(player.x + " " + player.y + " " + this._latlon + "<br>" );
					// if(CurrentTile != this){
						// $("#debug").html(CurrentTile._latlon);
						// CurrentTile = this;
					// }
				// }
					
				if(!this._active)
					return;
			},
			this.onHit("player", function() {
				// if(CurrentTile != this){
					// CurrentTile = this;
					// console.log(this._latlon);
				// }
			
					// item = collision[0];
			}));
			
			this.bind("KeyDown", function(e) {
				if(currentTile == this) {
				if(e.keyCode === Crafty.keys.Q) {
					var search = this.mbr(), results = Crafty.map.search({
						_x : search._x - MAPTILE,
						_y : search._y - MAPTILE,
						_w : search._w + MAPTILE,
						_h : search._h + MAPTILE,
					}, true), i = 0, l = results.length;
	
					//loop over entities search for the first car
					for(; i < l; ++i) {
						if(results[i].has("MapTile")) {
							console.log(results[i].y + " " + results[i].x)
							if(results[i].y < this.y)
								this._upTile = true;
							if(results[i].x < this.x)
								this._rightTile = true;
							if(results[i].y > this.y)
								this._downTile = true;
							if(results[i].x > this.x)
								this._leftTile = true;
	
						}
					}
					if(this._upTile != true){
						this.loadUpTile();
						console.log("up");
					}
					if(this._rightTile != true){
						this.loadRightTile();
						console.log("right");
					}
					if(this._downTile != true){
					console.log("down");
						this.loadDownTile();
					}
					if(this._leftTile != true){
						console.log("left");
						this.loadLeftTile();
					}
	
				}
			}
			if(currentTile == this){
				if(e.keyCode === Crafty.keys.S) {
					this.loadUpTile();
					this._upTile = true;
				}
				if(e.keyCode === Crafty.keys.Z) {
					this.loadRightTile();
					this._rightTile = true;
				}
				if(e.keyCode === Crafty.keys.X) {
					this.loadDownTile();
					this._downTile = true;
				}
				if(e.keyCode === Crafty.keys.C) {
					this.loadLeftTile();
					this._leftTile = true;
				}
			}
			});
			return this;
			// var name = ("map"+inix)+iniy;
			//Crafty.sprite(1, "maps/"+latlon+".png", { name :[0,0]});
			//this.loadLeftTile();
		},
		loadLeftTile : function(){
			loadMapTile(this._lat+','+(parseFloat(this._lon)+0.00429), this.x+MAPTILE, this.y);
		},
		loadRightTile : function(){
			loadMapTile(this._lat+','+(parseFloat(this._lon)-0.00429), this.x-MAPTILE , this.y);
		},
		loadUpTile : function(){
			loadMapTile(parseFloat(this._lat)+0.00345+','+this._lon, this.x, this.y-MAPTILE+5);
		},
		loadDownTile : function(){
			loadMapTile(parseFloat(this._lat)-0.00345+','+this._lon, this.x, this.y+MAPTILE-5);
		},
	
	});
			
	function loadMapTile(latlon, initx, inity) {
		$.ajax({
		type : "POST",
		url : "load_data.php",
		//dataType: "json",
		//async : false,
		data : "latlon="+latlon,
		success : function(msg) {
			polys = getPolys(msg,8);
			//MapTiles["maps/"+latlon+".png"]=(Crafty.e("MapTile, Canvas, map"+initx+inity).maptile(latlon, polys, initx, inity));
			var tile =  Crafty.e("MapTile, Canvas, map"+initx+inity).maptile(latlon, polys, initx, inity);
			MapTiles["maps/"+latlon+".png"] = tile;
		
//				tile.destroy();
			}
		});
	}
	function getPolys(msg, num) {
			polys = [];
			$("#poly").html(msg);
			$("path").each(function(i) {
				var path = this;
				polys.push(polygonSampledFromPath(path, num));
			});
			$("#poly").html(" ");
			//$("#poly").append(polys);
			return polys
	};
	
	function polygonSampledFromPath(path, samples) {
			var doc = path.ownerDocument;
			var poly = doc.createElementNS('http://www.w3.org/2000/svg', 'polygon');
	
			var points = [];
			var len = path.getTotalLength();
			if(len > 1000.0)
				samples = samples*2;
			var step = step = len / samples;
			for(var i = 0; i <= len; i += step) {
				var p = path.getPointAtLength(i);
				var point = [];
				point = [p.x / 10, p.y / 10];
				points.push(point);
				//p.x + ',' + p.y);
			}
			// poly.setAttribute('points', points.join(' '));
			// return poly;
			return points;
	};
	Crafty.c("Car", {
		_speed : 0,
		_active : false,
		_maxSpeed : 8,
		_handling : 0.8,
		_acceleration : 0.15,

		init : function() {
			this.addComponent("Keyboard, Solid, Collision").origin("center");
			this.collision(new Crafty.polygon([[2, 12], [7, 5], [16, 2], [27, 7], [30, 13], [29, 42], [29, 56], [24, 65], [7, 64], [1, 56], [3, 39], [2, 20]]));

			this.bind("EnterFrame", function() {
				if(!this._active)
					return;
				var slide = 0;

				if(this.isDown(Crafty.keys.W)) {
					this._speed += this._acceleration;
				}

				this._speed = this._speed * 0.98;

				if(this.isDown(Crafty.keys.S)) {
					this._speed -= this._acceleration;
				}

				if(this.isDown(Crafty.keys.SPACE)) {
					this._speed -= this._speed / 20;
					if(this._speed > this._maxSpeed / 2)
						slide = this._speed * 0.8;
				}

				if(this.isDown(Crafty.keys.A)) {
					this.rotation -= this._speed * this._handling + slide;
				}

				if(this.isDown(Crafty.keys.D)) {
					this.rotation += this._speed * this._handling + slide;
				}

				if(this._speed > this._maxSpeed) {
					this._speed = this._maxSpeed;
				}
				if(this._speed < -2) {
					this._speed = -2;
				}

				this.x += Math.sin(this._rotation * Math.PI / 180) * this._speed;
				this.y += Math.cos(this._rotation * Math.PI / 180) * -this._speed;

				//check for collision with houses
				var collision = this.hit("Solid"), item, diff, length, normal = {
					x : 0,
					y : 0
				};

				if(collision) {
					item = collision[0];

					normal.x = Math.sin(this._rotation * Math.PI / 180);
					normal.y = Math.cos(this._rotation * Math.PI / 180);
					diff = Math.sqrt(Math.pow(Math.abs(normal.x - item.normal.x), 2) * Math.pow(Math.abs(normal.y - item.normal.y), 2));

					//slow down based on the difference between directions
					this._speed = diff;

					this.x += Math.ceil(item.normal.x * -item.overlap);
					this.y += Math.ceil(item.normal.y * -item.overlap);

				}
			}).bind("KeyDown", function(e) {
				//already processed this key event
				if(LAST === e.timeStamp || !this._active)
					return;

				if(e.keyCode === Crafty.keys.F || e.keyCode === Crafty.keys.ENTER) {

					if(Math.abs(this._speed) < 1) {
						this._active = false;

						player.visible = true;
						player._active = true;
						player.x = this._x;
						player.y = this._y;
						CURRENT = player;
					}
				}
			});
		}
	});
};

